package org.honeynet.hbbackend.submithttp;

import java.io.IOException;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.honeynet.hbbackend.submithttp.SubmitHttpHandler.SubmissionValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@WebServlet(urlPatterns="/submit", loadOnStartup=1)
@MultipartConfig
public class SubmitHttpHandlerServlet extends HttpServlet {
	
	private static Logger log = LoggerFactory.getLogger(SubmitHttpHandlerServlet.class);
	
	@EJB
	SubmitHttpHandler handler;

//	@Override
//	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
//	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		AsyncContext actx = request.startAsync(request, response);
		log.trace("doPost() called");
		log.trace("post parts: {}", request.getParts());
		
//		SubmitHttpHandler handler = null;
//		try {
//			InitialContext ctx = new InitialContext();
//			handler = (SubmitHttpHandler) ctx.lookup("java:module/SubmitHttpHandler");
//		} catch (NamingException e) {
//			throw new ServletException(e);
//		}
		
		try {
			SubmitHttpReturnType ret = handler.handle(request);
			response.getWriter().print(ret.name());
			response.flushBuffer();
			return;
		} catch (SubmissionValidationException e) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "exception: SubmissionValidationException: " + e.getMessage());
			return;
		}
	}
	
}
